import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false,
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false,
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false,
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false,
      },
    ],
  },
  getters: {
    // 全选亮不亮
    isAll(state) {
      return state.goodList.every((item) => item.checked)
    },
    // 总价
    total(state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          return sum + item.price * item.num
        } else {
          return sum
        }
      }, 0)
    },
  },
  mutations: {
    // 全选
    changeChecked(state, name) {
      const good = state.goodList.find((item) => item.name === name)
      good.checked = !good.checked
    },
    changeAll(state, payload) {
      state.goodList.forEach((item) => {
        item.checked = payload
      })
    },
    // 加减
    changeNum(state, payload) {
      const good = state.goodList.find((item) => item.name === payload.name)
      good.num = good.num + payload.num < 1 ? good.num : good.num + payload.num
    },
    // 删除
    delGood(state, name) {
      state.goodList = state.goodList.filter((item) => item.name !== name)
    },
  },
})

export default store
